package com.yx.controller;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.yx.constatns.AuthConstatns;
import com.yx.constatns.OrderConstants;
import com.yx.entity.Order;
import com.yx.entity.OrderDetail;
import com.yx.feign.api.AddressService;
import com.yx.feign.api.CarService;
import com.yx.interceptor.DynamicDataSourceAnnotationInterceptor;
import com.yx.service.IOrderDetailService;
import com.yx.service.IOrderService;
import com.yx.vo.Address;
import com.yx.vo.Customer;
import com.yx.vo.OrderParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * @Classname OrderController
 * @Date 2021/07/19 19:56
 * @Author by yx
 * @Description TODO:
 */
@Controller
@RequestMapping("/orderController")
@Slf4j
public class OrderController {
    @Autowired
    private CarService carService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private DynamicDataSourceAnnotationInterceptor dynamicDataSourceInterceptor;

    @GetMapping("/orderConfirm")
    public String orderConfirm(String gid, HttpSession session, ModelMap modelMap) {
        //1.获取用户勾选的商品
        List<String> carArray = new ArrayList<>();
        if (!StringUtils.isEmpty(gid)) {
            //有id传递过来,
            String[] split = gid.split(",");
            carArray = Arrays.asList(split);
        }

        //2.获取当前登录用户
        Customer customer = (Customer) session.getAttribute(AuthConstatns.AUTH_SESSION);

        if (customer == null) {
            // 没有登录就跳转到登录页面
            return "redirect:http://localhost/auth/login.html";
        }

        //3.查询用户地址
        List<Address> addressList = addressService.getAddressListByUid(customer.getId());
        //4.查询用户购物车

        Map<String, Object> carMap = null;
        if (carArray.size() > 0) {
            //用户勾选了商品
            carMap = carService.getCarListByUidAndGid(customer.getId(), carArray);
        } else {
            //用户没有勾选购物车,直接提交订单
            carMap = carService.getCarListByUid(customer.getId());
        }

        log.debug("{}", carMap);

        modelMap.put("carMap", carMap);
        modelMap.put("addressList", addressList);

        return "order";
    }

    @GetMapping("/createOrder")
    public String createOrder(OrderParam orderParam, HttpSession session) throws ExecutionException, InterruptedException {
        //获取当前登录用户
        Customer customer = (Customer) session.getAttribute(AuthConstatns.AUTH_SESSION);
        // 判断用户是否登录
        if (customer == null) {
            return "redirect:http://localhost/auth/login.html";
        }

        //3.创建一个订单
        String oid = orderService.createOrder(orderParam,customer.getId());
        log.debug("发送至pay的oid:{}", oid);
        return "redirect:http://localhost/pay/ali/pay?oid="+oid;
//        return "redirect:http://localhost/pay/weixin/unifiedOrder?oid="+oid;
    }


    @GetMapping("/getOrderByOid/{oid}")
    @ResponseBody
    public Order getOrderByOid(@PathVariable String oid){
        Integer tableIndex = dynamicDataSourceInterceptor.getTableIndex();
        return orderService.getOrderByOid(oid);
    }

    @PostMapping("/getOrderDetailListByOid")
    @ResponseBody
    public List<OrderDetail> getOrderDetailListByOid(String oid){
        Integer tableIndex = dynamicDataSourceInterceptor.getTableIndex();
        return orderDetailService.getOrderDetailListByOid(oid,tableIndex);
    }

    @PostMapping("/updateOrderStatus")
    @ResponseBody
    public void updateOrderStatus(@RequestParam("out_trade_no") String out_trade_no, @RequestParam("status") Integer status){

        log.debug(out_trade_no.substring(13,17));
        // 从订单号中截取uid
        Integer uid = Integer.valueOf(out_trade_no.substring(13,17));
        // 计算数据库编号(用户id后四位%数据库的数量)
        Integer dbIndex = (uid % OrderConstants.ORDER_DB_SIZE) + 1;

        // 创建数据源key
        String dataSourceKey = OrderConstants.ORDER_DB_PRE + dbIndex;

        // 设置数据源
        DynamicDataSourceContextHolder.push(dataSourceKey);

        // 计算订单的表的编号(在插入的时候才会使用这个值，我在这个地方一起计算出来)
        Integer tableIndex = (uid / OrderConstants.ORDER_DB_SIZE % OrderConstants.ORDER_TABLE_SIZE) + 1;

        orderService.updateOrderStatus(out_trade_no,status);
    }

    @GetMapping("/wxgetOrderByOid/{oid}")
    @ResponseBody
    public Order wxgetOrderByOid(@PathVariable String oid){
        // 从订单号中截取uid
        Integer uid = Integer.valueOf(oid.substring(13,17));
        // 计算数据库编号(用户id后四位%数据库的数量)
        Integer dbIndex = (uid % OrderConstants.ORDER_DB_SIZE) + 1;

        // 创建数据源key
        String dataSourceKey = OrderConstants.ORDER_DB_PRE + dbIndex;

        // 设置数据源
        DynamicDataSourceContextHolder.push(dataSourceKey);

        // 计算订单的表的编号(在插入的时候才会使用这个值，我在这个地方一起计算出来)
        Integer tableIndex = (uid / OrderConstants.ORDER_DB_SIZE % OrderConstants.ORDER_TABLE_SIZE) + 1;

        return orderService.getOrderByOid(oid);
    }


    public static void main(String[] args) {
        String s = "2021072183585000610";
        System.out.println(s.substring(13, 17));
    }
}
